import React from 'react';

import { Modal, Form, Button, Input, Tooltip, Cascader, Upload, notification as Notification } from 'antd';

import { FormInstance } from 'antd/lib/form';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { saveBookInfo } from '../../../api/bookInfo';
import { bookClassificationTreeVo } from '../../../api/bookClassification';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

class BookAdd extends React.Component {
  state = {
    cascaderId: null,
    cascaderOptions: [],
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
    formData: new FormData()
  };

  formRef = React.createRef(FormInstance);

  constructor(props) {
    super(props);
    this.state = {
      cascaderOptions: [],
      cascaderId: null,
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList: [],
      formData: new FormData()
    };
    this.getBookClassification();
  }

  getBookClassification = () => {
    bookClassificationTreeVo().then(({ data }) => {
      function deleteEmptyChildren(records) {
        records.forEach((record) => {
          if (record && record.children) {
            if (record.children.length <= 0) {
              delete record.children;
            } else {
              deleteEmptyChildren(record.children);
            }
          }
        });
      }

      deleteEmptyChildren(data);
      this.setState({
        cascaderOptions: data
      });
    }).catch((e) => {
      console.log(e, typeof e, 'e');
    });
  }

  save = () => {
    const form = this.formRef.current;
    const { formData } = this.state;

    form.validateFields().then((values) => {

      const { classificationId } = values;
      if (classificationId.length > 0) {
        values.classificationId = classificationId.pop();
      }

      for (let key in values) {
        formData.set(key, values[key]);
      }
      saveBookInfo(formData).then(({ data }) => {
        Notification.success({
          message: `添加 ${data.name} 成功`,
          duration: 2
        });
        form.resetFields();

        this.setState({
          fileList: []
        });
      }).catch((e) => {
        console.log(e, typeof e, 'e');
      });
    }).catch((errorInfo) => {
      const { errorFields } = errorInfo;
      Notification.error({
        message: errorFields[0].errors[0],
        duration: 2
      });
    });
  };

  handleChange = ({ fileList }) => {
    const { formData } = this.state;
    const file = fileList[0];
    if (file) {
      formData.set('file', file.originFileObj, file.name);
    } else {
      formData.delete('file');
    }
    this.setState({ fileList, formData });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async(file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  onCascaderChange = (value, selectedOptions) => {
    const cascaderId = value.pop();
    value.push(cascaderId);
    this.setState({
      cascaderId
    });
  }

  render() {
    const { previewVisible, previewImage, fileList, previewTitle, cascaderOptions, cascaderId } = this.state;

    const initialValues = {};

    return (
      <>
        <Form
          ref={this.formRef}
          {
            ...{
              labelCol: { span: 2 },
              wrapperCol: { span: 8 },
            }
          }
          name="editForm"
          initialValues={{ ...initialValues }}
          scrollToFirstError
        >
          <Form.Item
            name="name"
            label="书籍名称"
            rules={[{ required: true, message: '请输入书籍名称!', whitespace: true }]}
            hasFeedback
          >
            <Input/>
          </Form.Item>
          <Form.Item
            name="isbn"
            label={
              <span>ISBN&nbsp;
                <Tooltip title="唯一的编号">
                  <QuestionCircleOutlined/>
                </Tooltip>
              </span>
            }
            rules={[
              {
                required: true,
                message: '请输入ISBN编号!',
                whitespace: true
              },
            ]}
            hasFeedback
          >
            <Input/>
          </Form.Item>
          <Form.Item
            label="书籍分类"
            name="classificationId"
            rules={[({ getFieldValue }) => ({
              validator(rule, value) {
                if (cascaderId > 0) {
                  return Promise.resolve();
                }
                return Promise.reject('请选择书籍分类!');
              },
              required: true,
              validateTrigger: 'onBlur'
            })
            ]}
          >
            <Cascader
              options={cascaderOptions}
              placeholder="请选择书籍分类"
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children'
              }}
              onChange={this.onCascaderChange}
            />
          </Form.Item>
          <Form.Item
            name="author"
            label="作者"
            rules={[{ required: true, message: '请输入书籍作者!', whitespace: true }]}
            hasFeedback
          >
            <Input/>
          </Form.Item>
          <Form.Item
            name="publisher"
            label="出版社"
            rules={[{ required: true, message: '请输入书籍出版社!', whitespace: true }]}
            hasFeedback
          >
            <Input/>
          </Form.Item>
          <Form.Item label={
            <span>封面图片&nbsp;
              <Tooltip title="支持JPG/PNG图片上传。">
                <QuestionCircleOutlined/>
              </Tooltip>
            </span>
          }>
            <Upload
              accept=".jpg,.png,.jpeg"
              action=""
              listType="picture-card"
              fileList={fileList}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
              beforeUpload={() => false}
            >
              {fileList.length >= 1 ? null : (
                <div>
                  <PlusOutlined/>
                  <div style={{ marginTop: 8 }}>上传</div>
                </div>
              )}
            </Upload>
            <Modal
              visible={previewVisible}
              title={previewTitle}
              footer={null}
              onCancel={this.handleCancel}
            >
              <img alt="example" style={{ width: '100%' }} src={previewImage}/>
            </Modal>
          </Form.Item>
          <Form.Item
            name="words"
            label="字数"
            hasFeedback
          >
            <Input/>
          </Form.Item>
          <Form.Item
            name="desc"
            label="书籍描述信息"
            hasFeedback
          >
            <Input.TextArea/>
          </Form.Item>

          <Form.Item {...{ wrapperCol: { offset: 2 }, }}>
            <Button type="primary" htmlType="submit" onClick={this.save}>
              确定
            </Button>
          </Form.Item>
        </Form>
      </>
    );
  }
}

export default BookAdd;
